#include "../include/udpclient.h"
#include<QNetworkDatagram>
#include<QTimer>

UDPClient::UDPClient(QObject *parent)
    : QUdpSocket{parent}
{
    m_udpClientSock=new QUdpSocket(this);
    m_udpClientSock->bind(QHostAddress::LocalHost,3355);
    count=0;

//    for(int i=0;i!=10;++i)
//        this->login("你好！");
    //this->login("abcde");

    QTimer *time=new QTimer(this);
    time->start(2000);
    connect(time,&QTimer::timeout,this,[this]{this->login("你好！");});
    connect(m_udpClientSock,SIGNAL(readyRead()),this,SLOT(readPendingDatagrams()));
}

UDPClient::~UDPClient()
{
    //delete m_udpClientSock;
    m_udpClientSock->close();
}

void UDPClient::login(const QString& msg)
{
    QString headFormat=QString(QString::number(++count).toUtf8()+"-")+QString("127.0.0.1-")+QString("LOGIN: --");
    QString tailFormat=QString("-- :end-127.0.0.1-"+QString::number(count).toUtf8());

    QNetworkDatagram nd((headFormat+msg+tailFormat).toUtf8(),QHostAddress::LocalHost,7755);
    int len=m_udpClientSock->writeDatagram(nd);
    qDebug()<<((headFormat+msg+tailFormat).size());
}

void UDPClient::readPendingDatagrams()
{
    if(m_udpClientSock->hasPendingDatagrams()){
        QNetworkDatagram data=m_udpClientSock->receiveDatagram();
        if(!data.isValid()){
            qDebug()<<m_udpClientSock->localPort()<<m_udpClientSock->error();
            //m_udpClientSock->writeDatagram(data.makeReply("0"));
            return;
        }
        qDebug()<<QString::fromUtf8(data.data());
    }
}
